layui.define(['jquery', 'form', 'layer'], function(exports) {
    var $ = layui.jquery,
        form = layui.form,
        layer = layui.layer;

    function init() {
        bindEvents();
    }

    function bindEvents() {
        // 登录表单提交
        $('#loginForm').on('submit', function(e) {
            e.preventDefault();
            var formData = {
                username: $('#username').val(),
                password: $('#password').val()
            };

            // 清除错误信息
            $('.error-message').hide();

            // 验证表单
            if (!formData.username) {
                $('#username-error').text('请输入用户名').show();
                return;
            }
            if (!formData.password) {
                $('#password-error').text('请输入密码').show();
                return;
            }

            // 发送登录请求（application/x-www-form-urlencoded）
            console.log('发送登录请求:', formData);
            $.ajax({
                url: '/user/login',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(res) {
                    console.log('登录响应:', res);
                    if (res.code === 200) {
                        $('#success-message').text('登录成功，正在跳转...').show();
                        
                        // 保存用户信息到localStorage
                        if (res.data) {
                            localStorage.setItem('userInfo', JSON.stringify(res.data));
                            console.log('用户信息已保存:', res.data);
                        }
                        
                        setTimeout(function() {
                            console.log('准备跳转到dashboard.html');
                            window.location.href = 'dashboard.html';
                        }, 1000);
                    } else {
                        $('#password-error').text(res.message || '登录失败').show();
                    }
                },
                error: function(xhr, status, error) {
                    console.error('登录请求失败:', xhr, status, error);
                    $('#password-error').text('网络错误，请稍后重试').show();
                }
            });
        });

        // 注册按钮点击
        $('#registerBtn').on('click', function() {
            showRegisterDialog();
        });
    }

    function showRegisterDialog() {
        var registerHtml = `
            <form class="layui-form" id="registerForm" style="padding: 20px;">
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-block">
                        <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">手机号</label>
                    <div class="layui-input-block">
                        <input type="text" name="phone" required lay-verify="required|phone" placeholder="请输入手机号" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">真实姓名</label>
                    <div class="layui-input-block">
                        <input type="text" name="realName" placeholder="请输入真实姓名" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">邮箱</label>
                    <div class="layui-input-block">
                        <input type="email" name="email" lay-verify="email" placeholder="请输入邮箱" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">性别</label>
                    <div class="layui-input-block">
                        <input type="radio" name="gender" value="1" title="男" checked>
                        <input type="radio" name="gender" value="0" title="女">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">地址</label>
                    <div class="layui-input-block">
                        <input type="text" name="address" placeholder="请输入地址" autocomplete="off" class="layui-input">
                    </div>
                </div>
            </form>
        `;

        layer.open({
            type: 1,
            title: '用户注册',
            area: ['500px', '400px'],
            content: registerHtml,
            btn: ['注册', '取消'],
            success: function(layero, index) {
                form.render();
            },
            yes: function(index, layero) {
                var formData = {};
                layero.find('input').each(function() {
                    var name = $(this).attr('name');
                    var value = $(this).val();
                    if (name) {
                        if ($(this).attr('type') === 'radio') {
                            if ($(this).prop('checked')) {
                                formData[name] = value;
                            }
                        } else {
                            formData[name] = value;
                        }
                    }
                });

                // 发送注册请求
                $.ajax({
                    url: '/user/register',
                    type: 'POST',
                    data: formData,
                    success: function(res) {
                        if (res.code === 200) {
                            layer.msg('注册成功', {icon: 1});
                            layer.close(index);
                        } else {
                            layer.msg(res.message || '注册失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('网络错误，请稍后重试', {icon: 2});
                    }
                });
            }
        });
    }

    exports('login', { init: init });
});
